<template>
  <!-- 待定预约 -->
  <workStatistics :todayData="today"></workStatistics>
  <zsearch v-loading="loading">
      <template #title>
        <span>待定预约</span>
      </template>
      <template #date>
        <el-date-picker
            class="date-1"
            type="date"
            v-model="date"
            placeholder="选择日期"
            @change="handleChangeDate"
            >
        </el-date-picker>
      </template>
      <template #select>
        <el-input class="input-1" v-model="name" placeholder="患者/电话/病历号"></el-input>
        <el-select class="select-1" v-model="doctorId" clearable filterable placeholder="选择医生">
          <el-option
            v-for="item in optionsDoctor"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </template>
      <template #btns>
        <el-button class="btn-1" @click="hanledSearch">查询</el-button>
	      <el-button class="btn-2">导出</el-button>
      </template>
      <template #table>
        <ztable 
          :tableData='data' 
          :strucs='columns'
          :height="'100%'"
          :isshowOperation="true"
          @onToDetail="onToDetail"
        >
          <template #default="slotScope">
            <el-button type="text" class="operation" @click="handleResetAppoint(slotScope.rowData)">重新预约</el-button>
            <el-button type="text" class="operation" >删除</el-button>
          </template>
        </ztable>
        
      </template>
      <template #page>
        <zpage 
            :currentPage="current" 
            :total="total" 
            :pageSize="size"
            @handleSizeChange="handleSizeChange" 
            @handleCurrentChange="handleCurrentChange"
        ></zpage>
      </template>
    </zsearch>


    <!-- 新增/挂号/ 预约/  -->
  <el-drawer
			size="45%"
			:title="title"
			v-model="showDrawer"
			:before-close="drawerClose" destroy-on-close>
			<zaddpatient 
					@cancel="cancel" 
					@saveMakeAnAppointment="saveMakeAnAppointment" 
					@saveAndRegister="saveAndRegister"
					v-if="isADD === 'add'"
					></zaddpatient>
			
			<zregister v-if="isADD === 'register'"
				@cancel="cancel" 
				@handlebtn="handlebtn"
				></zregister>

			<zmakeanapp v-if="isADD === 'makeanapp'"
				@handlebtn="handlebtn"
				@cancel="cancel"
        @reloadList="reloadList"
        :makeanappInfo="makeanappInfo"

				></zmakeanapp>
	</el-drawer>

</template>

<script lang='ts'>
import { defineComponent, reactive, toRefs, ref } from '@vue/runtime-core'

import useRequet, { RespData } from "../../hook/network"
import { debounce } from "../../utils/debounce"

import useConfgin from '../../hook/getconfig'

import ztable from '@components/Table/index.vue'
import zpage from '@components/pagination/pagination.vue'
import zsearch from '@components/search/search.vue'

import zmakeanapp from "../../components/patient/makeAnAppointment.vue"
import zaddpatient from "../../components/patient/add.vue"
import zregister from "../../components/patient/register.vue"

import workStatistics from "../../components/workStatistics/work.vue"

import { getNowDate } from '../../utils/nowDate'
import { Option } from '../../types/index'
import { getDoctors } from "../../usefn/getDoctor"
import useSetAddLog from "../../hook/setAddLog"
import { useRouter } from 'vue-router'

import { ElMessage, ElMessageBox } from 'element-plus'

const ID = 501

export default defineComponent({
  name: 'BePending',
  components: {
    ztable,
    zpage,
    zsearch,

    zmakeanapp,
    zaddpatient,
    zregister,

    workStatistics,
  },
  setup() {
    const router = useRouter()
    let search = reactive({
      date: '',
      name:'',
      current: 1,
      size: 10,
      total: 0,

      doctorId: null,
      optionsDoctor: [] as Option[],

      loading: false
    })
    let today = reactive({
      todayNewCustomer: 0,
      todayNewSub: 0,
      todayNewCollection: 0,
      todayNewAccessLog: 0,
      todayNewSickMedicalRecords: 0
    })
    const data = ref([])
    // const columns = useConfgin(ID)
    const columns = [
      {
           id: 529,
            name: "customerName",
            viewName: "姓名",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null
        },
        {
           id: 529,
            name: "customerHistorySickNum",
            viewName: "病历号",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null
        },
        {
           id: 529,
            name: "customerPhone",
            viewName: "手机",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null
        },
        {
           id: 529,
            name: "subscribeTime",
            viewName: "待定日期",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null
        },
        {
           id: 529,
            name: "createTime",
            viewName: "创建日期",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null
        },
        {
           id: 529,
            name: "doctorName",
            viewName: "预约医生",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null
        },
        {
           id: 529,
            name: "itemNames",
            viewName: "预约项目",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null
        },
        {
           id: 529,
            name: "remark",
            viewName: "备注",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null
        },
    ]

    const getdoctor = async() => {
      search.optionsDoctor = await getDoctors()
    }
    getdoctor()

    const request = useRequet({ path: "" });

    const req = () => {
      search.loading = true
      let params = {
        beforePlanDate: search.date,
        size: search.size,
        current: search.current,
        customerQueryValue: search.name,
        doctorId: search.doctorId,
      }
      request.sendRequest({
        address: '/customer/subscribe/getUndeterminedSubScribePageBySubCompanyId',
        params,
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
					data.value = resp.data.records
          search.total = resp.data.total
          search.current = resp.data.current
          console.log(data)

          search.loading = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
          
        },
        method: "POST",
      })
    }
    req()

    // 去详情
    const onToDetail = (id: number) => {
      useSetAddLog(id)
      router.push(`/allPatientDetails/${id}/patient`)
    }

    const getTodayStatistics = () => {
      request.sendRequest({
        address: '/pay/order/todayStatistics',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
	
          console.log(resp.data)
          today.todayNewCustomer = resp.data.todayNewCustomer
          today.todayNewSub = resp.data.todayNewSub
          today.todayNewCollection = resp.data.todayNewCollection
          today.todayNewAccessLog = resp.data.todayNewAccessLog
          today.todayNewSickMedicalRecords = resp.data.todayNewSickMedicalRecords

          search.loading = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
          
        },
        method: "POST",
      })
    }
    getTodayStatistics()

    const debounceRefresh = debounce(req, 1000)
    //搜索
    const hanledSearch = () => {
      debounceRefresh()
    }

    // 分页
    const handleCurrentChange = (val: number) => {
			search.current = val
      req()
			console.log('handleCurrentChange', val)
		}
    const handleSizeChange = (val: number) => {
      search.size = val
      req()
			console.log('handleSizeChange', val)
		}

    const handleChangeDate = (e: Date) => {
      search.date = getNowDate(e)
    }

    const handleResetAppoint = (RowData: any) => {
      console.log(RowData)
      let date = new Date()
      let nowDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:00 `

      let echoInfo = {
        id: RowData.id,
        customerId: RowData.customerId,
        customerName: RowData.customerName,
        clinicType: RowData.clinicType,
        subscribeType: RowData.subscribeType,
        subscribeTime: nowDate,
        timeLength: '',
        consultantId: '',
        departmentId: '',
        doctorId: RowData.doctorId,
        nurseId: '',
        remark: '',
        itemIdsShow: [],
        clickType: '新建预约'
      }

      console.log(echoInfo)
      makeanappInfo.value = echoInfo
      showDrawer.value = true
      title.value = "新建预约"
      isADD.value = 'makeanapp'
    }

    const makeanappInfo = ref({} as any)
       // 刷新列表
    const reloadList = () => {
      console.log('执行')
      req()
    }

    // 抽屉 --》 新建预约部分
    const showDrawer = ref(false)
    const title = ref('')
    const isADD = ref('')
    // 打开新建预约
    const saveMakeAnAppointment = () => {
      isADD.value = 'makeanapp'
			title.value = "新建预约"
    }

    const saveAndRegister = () => {
			isADD.value = 'register'
			title.value = "挂号"
		}


    const handlebtn = () => {
      isADD.value = 'add'
			title.value = "个人信息"
    }
    const drawerClose = () => {
      ElMessageBox.confirm('此操作将关闭窗口, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
				showDrawer.value = false
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
    }
    const cancel = () => {
      showDrawer.value = false
    }
    return {
      data,
      columns,
      ...toRefs(search),
      today,
      onToDetail,

      handleCurrentChange,
      handleSizeChange,
      hanledSearch,

      showDrawer,
      title,
      isADD,
      saveMakeAnAppointment,
      saveAndRegister,
      handlebtn,
      drawerClose,
      cancel,
      makeanappInfo,
      reloadList,

      handleResetAppoint,

      handleChangeDate
    }
  }
})
</script>

<style lang="scss" scoped>
.select-1 {
  padding-left: 8px;
}
</style>